#!/bin/sh

name=buildbot

msg() {
    echo "--> $0:" $*
}

cd_approot() {
    cd master
}

create_virtualenv() {
    local env_directory="$HOME/env"

    msg "creating virtualenv"
    if [ ! -d $env_directory ] ; then
        virtualenv $env_directory
        $env_directory/bin/pip install -E $env_directory pip --upgrade
    fi

    . $env_directory/bin/activate
}

install_dependencies() {
    local download_cache="$HOME/.pip/downloads/"

    msg "installing dependencies"
    if [ -f requirements.txt ] ; then
        [ -d $download_cache ] || mkdir -p $download_cache
        pip install --quiet --download-cache=$download_cache -r requirements.txt
    fi

    # We can't install the latest version of buildbot with pip because the
    # setup.py is not in the root directory.
    # -e git+git://github.com/buildbot/buildbot.git#egg=buildbot
    local buildbot_repo="$HOME/buildbot"
    if [ ! -d $buildbot_repo ] ; then
        msg "installing buildbot"
        mkdir -p $buildbot_repo
        git clone git://github.com/buildbot/buildbot.git $buildbot_repo
        ( cd "$buildbot_repo/master" ; exec python setup.py install )
    fi
}

install_application() {
    msg "installing application to ~/"
    rsync -aH --delete --exclude "data" * $HOME/
    # buildbot doesn't have an option to specify another path for
    # master.cfg, so simply symlinkg it.
    ln -snf ~/master-dotcloud.cfg ~/master.cfg
}

migrate_database() {
    msg "migrating database"
    # You must specify the --db option here when you don't use sqlite.
    # "--db=postgresql+psycopg2://$DOTCLOUD_DB_SQL_LOGIN:$DOTCLOUD_DB_SQL_PASSWORD@$DOTCLOUD_DB_SQL_HOST:$DOTCLOUD_DB_SQL_PORT/template1"
    # (Seems to be not necessary after buildbot >= 0.8.5)
    buildbot upgrade-master ~/
}

cd_approot
create_virtualenv
install_dependencies
install_application
migrate_database
